package com.my.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@ServerEndpoint("/ws/park")
@Component
public class WebSocketClient {

    //@Autowired
    //private WebSocketServer webSocketServer;//每次/ws/park被访问都会创建一个新的WebSocketClient，新创建的Client不会被Spring注入

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;

    public Session getSession() {
        return session;
    }

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        WebSocketClients.addClient(this);
        System.out.println("客户端" + session.getId() + "连接成功");
        System.out.println("在线客户端数量：" + WebSocketClients.getOnlineCount());
    }

    @OnClose
    public void onClose() {
        WebSocketClients.removeClient(this);
        System.out.println("客户端" + session.getId() + "退出");
    }

    //收到客户端消息的方法
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("收到客户端[" + session.getId() + "]的消息：");
        System.out.println(message);
    }

    @OnError
    public void onError(Session session, Throwable e) {
        System.err.println("客户端[" + session.getId() + "]出现错误：");
        e.printStackTrace();
    }

    //主动向客户端发送消息
    public void sendMessage(String message) throws IOException {
        if (session.isOpen()) {
            this.session.getBasicRemote().sendText(message);
        }
    }
}
